//引入第三方包
const express = require('express');
const fs = require('fs');
const path = require('path');
//实例化
let app = express();
//设置静态资源文件夹
app.use(express.static('static'));
//设置post请求中间件
app.use(express.json());
app.use(express.urlencoded({ extended: false }));


//设置端口
//注册
app.post('/zhuce', (req, res) => {
    let { name } = req.body;
    console.log(req.body);

    let filepath = path.join(__dirname, './json/users.json');
    let arr = fs.readFileSync(filepath);
    arr = arr.toString() ? JSON.parse(arr) : [];

    let i = arr.findIndex((item) => {
        return item.name == name;
    })
    if (i != -1) {
        res.send({ code: 400, msg: '用户已存在，注册失败！' })
    } else {
        arr.push(req.body);
        fs.writeFileSync(filepath, JSON.stringify(arr), 'utf8');
        res.send({ code: 200, msg: '注册成功!' });
    }
})

//登录
app.post('/denglu', (req, res) => {
    let { name, pass } = req.body;

    let filepath = path.join(__dirname, './json/users.json');
    let arr = fs.readFileSync(filepath);
    arr = arr.toString() ? JSON.parse(arr) : [];

    let i = arr.findIndex((item, index) => {
        return item.name == name && item.pass == pass;
    })
    if (i != -1) {
        console.log(arr[i]);
        res.send({ code: 200, msg: '登陆成功!', userinfo: arr[i].name });
    } else {
        res.send({ code: 400, msg: '登陆失败!' });
    }
})

let filepath = path.join(__dirname, './json/admin.json');
let arr = fs.readFileSync(filepath);
arr = arr.toString() ? JSON.parse(arr) : [];

//新增
app.post('/add', (req, res) => {
    let { name } = req.body;

    let filepath = path.join(__dirname, './json/admin.json');
    let arr = fs.readFileSync(filepath);
    arr = arr.toString() ? JSON.parse(arr) : [];

    let i = arr.findIndex((item) => {
        return item.name == name;
    })
    if (i != -1) {
        res.send({ code: 400, msg: '岗位已存在，新增失败！' })
    } else {
        arr.push(req.body);
        fs.writeFileSync(filepath, JSON.stringify(arr), 'utf8');
        res.send({ code: 200, msg: '新增成功!' });

    }
})


//渲染请求
app.get('/list', (req, res) => {
    let { page, count } = req.query;

    let filepath = path.join(__dirname, './json/admin.json');
    let arr = fs.readFileSync(filepath);
    arr = arr.toString() ? JSON.parse(arr) : [];

    let newarr = arr.slice((page - 1) * count, page * count);
    res.send({ code: 200, msg: '请求成功!', list: newarr });
})

//搜索
app.get('/search', (req, res) => {
    let { searchkey } = req.query;

    let filepath = path.join(__dirname, './json/admin.json');
    let arr = fs.readFileSync(filepath);
    arr = arr.toString() ? JSON.parse(arr) : [];

    let newarr = arr.filter((item) => {
        return new RegExp(searchkey).test(item.name);
    })
    res.send({ code: 200, msg: '查询成功!', list: newarr });
})



//设置监听
app.listen(2022, () => { console.log('服务端运行在: http://localhost:2022'); })